package com.gabry.goodkill.actor
import java.io.RandomAccessFile
import java.nio.MappedByteBuffer
import java.nio.channels.FileChannel

import akka.actor.{Actor, ActorLogging}
import com.gabry.goodkill.protocol._

import scala.util.Try

/**
 * Created by gabry on 2018/9/20 16:29
 */
class CacheActor(activity:ACTIVITY_ID_TYPE,cacheId:Int) extends Actor with ActorLogging{
  // 1MB = 838,8608
  private val debug = true
  private val BIT_SIZE = 8388608
  private var mmapFile:Option[FileChannel] = None
  private var mappedByteBuffer:Option[MappedByteBuffer] = None
  override def preStart(): Unit = {
    mmapFile = Try(new RandomAccessFile(s"logs/activity-$activity-$cacheId.bit","rws").getChannel).toOption
    mmapFile.foreach(channel=> mappedByteBuffer = Try(channel.map(FileChannel.MapMode.READ_WRITE,0,BIT_SIZE)).toOption)
  }

  override def postStop(): Unit = {
    mmapFile.foreach{ channel =>
      Try{
        channel.force(true)
        channel.close()
      }
    }
    mappedByteBuffer.foreach(_.clear())
  }
  private def registerOrder(order:PlaceOrder):Boolean = {
    if(debug){
      true
    }else
      mappedByteBuffer match {
      case Some(buffer) =>
        buffer.put(order.userKillId,1.toByte)
        true
      case None => false
    }
  }
  override def receive: Receive = {
    case order @ PlaceOrder(userKillId,activityId,goodKillId) =>
      if(registerOrder(order)){
        sender ! Purchased(userKillId,Good(goodKillId,activityId))
      }else {
        sender() ! PurchaseFailed
      }
  }
}
